package com.huluobo.jetpackdemo.lifecycle

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.lifecycle.ViewModelProvider
import com.huluobo.jetpackdemo.MainActivity
import com.huluobo.jetpackdemo.R

class ADActivity : AppCompatActivity() {
    lateinit var adManager: ADManager
    private lateinit var adViewModel: ADViewModel
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_ad)

        val time = findViewById<TextView>(R.id.time)
        val cancel = findViewById<Button>(R.id.cancel)

        adViewModel = ViewModelProvider(this)[ADViewModel::class.java]

        adManager = ADManager(adViewModel)
        //观察者模式三要素,被观察者是当前Activity,由于ComponentActivity已经实现了LifecycleOwner接口(宿主接口,被观察者)
        //同各国lifecycle.addObserver(adManager) 实现订阅关系
        //观察者是adManager,实现了LifecycleObserver

        lifecycle.addObserver(adManager)

        adViewModel.timingResult.observe(this) {
            time.text = "广告剩余时间:${it / 1000}秒"
            adViewModel.timing = it
            if (it / 1000 <= 1) {
                val intent = Intent(this@ADActivity, MainActivity::class.java)
                this@ADActivity.startActivity(intent)
                this@ADActivity.finish()
            }
        }

//        adManager.adManagerListener = object : ADManager.ADManagerListener {
//            override fun timing(second: Int) {
//                time.text = "广告剩余时间:${second}秒"
//                adViewModel.timing = second.toLong() * 1000
//            }
//
//            override fun finish() {
//                val intent = Intent(this@ADActivity, MainActivity::class.java)
//                this@ADActivity.startActivity(intent)
//                this@ADActivity.finish()
//            }
//        }

        cancel.setOnClickListener {
            val intent = Intent(this, MainActivity::class.java)
            startActivity(intent)
            finish()
        }

    }
}